<template>
  <div id='commodityListDetail' class="createPost-container">
    <el-form ref="postForm" :model="formParams" class="form-container" label-width="134px">
      <div class="createPost-main-container">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formParams.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品售价" prop="priceFormat">
          <el-input v-model="formParams.priceFormat" placeholder="请输入商品售价"></el-input>
        </el-form-item>
        <el-form-item label="商品原价" prop="originalPriceFormat">
          <el-input v-model="formParams.originalPriceFormat" placeholder="请输入商品原价"></el-input>
        </el-form-item>
        <el-form-item label="结算价格" prop="settlePriceFormat">
          <el-input v-model="formParams.settlePriceFormat" placeholder="请输入商品的奖励价格"></el-input>
        </el-form-item>
        <el-form-item prop="title" label="商品封面">
          <el-upload
            class="avatar-uploader"
            name="file"
            :action="uploadAction"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="formParams.coverImage" :src="formParams.coverImage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            400*400大小图片
          </el-upload>
        </el-form-item>
        <el-form-item prop="title" label="轮播图片">
          <el-upload
            class="avatar-uploader"
            name="file"
            :action="uploadAction"
            :headers="headers"
            :show-file-list="false"
            :on-success="aa"
            :before-upload="beforeAvatarUpload">
            <div class="imgWrap" v-if="imgList.length>0">
              <div class="imgBox" v-for="(src,index) in imgList" :key="index">
                <img :src="src" alt="">
                <i class="el-icon-plus el-icon-remove" @click.stop="deleteImg(index)"></i>
              </div>


            </div>

            <!--<img v-if="formParams.cover" :src="formParams.cover" class="avatar">-->
            <div v-if="imgList.length<5">
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <span>请上传1到5张520*516宽高大小图片</span>
            </div>

          </el-upload>
        </el-form-item>

        <el-form-item label="商品详情" prop="detail">
          <Tinymce id="Tinymce" v-model="formParams.detail" :height="300" ref="Tinymce"/>
        </el-form-item>

        <el-form-item label="商品排序" prop="queue">
          <el-input v-model="formParams.queue" placeholder="数字越小，排序越靠前"></el-input>
        </el-form-item>

        <el-form-item label="销售数量基数" prop="baseSaleCount">
          <el-input v-model="formParams.baseSaleCount" placeholder="销售数量基数"></el-input>
        </el-form-item>
        <el-form-item label="成团人数" prop="groupBuySuccess">
          <el-input v-model="formParams.groupBuySuccess" placeholder="成团人数"></el-input>
        </el-form-item>
        <el-form-item label="成功中签人数" prop="groupBuySuccessUser">
          <el-input v-model="formParams.groupBuySuccessUser" placeholder="成功中签人数"></el-input>
        </el-form-item>
        <el-form-item label="拼团失败奖励金额" prop="groupBuyFailedAwardFormat">
          <el-input v-model="formParams.groupBuyFailedAwardFormat"
                    placeholder="拼团失败奖励金额，0.3元-5000元区间有效，其他金额无效"></el-input>
          <div style="color: grey">拼团失败奖励金额，0.3元-5000元区间有效，其他金额无效</div>
        </el-form-item>
        <el-form-item label="拼团成团公益金额" prop="groupBuyContributionFormat">
          <el-input v-model="formParams.groupBuyContributionFormat" placeholder="拼团成团公益金额"></el-input>
        </el-form-item>
        <el-form-item label="拼团成团分红金额" prop="groupBuyBonusFormat">
          <el-input v-model="formParams.groupBuyBonusFormat" placeholder="拼团成团分红金额"></el-input>
        </el-form-item>
        <el-form-item label="开售时间" prop="startSaleTime">
          <el-date-picker
            v-model="formParams.startSaleTimeDate"
            type="datetime"
            placeholder="选择开售时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="上架">
          <el-checkbox v-model="formParams.enable"></el-checkbox>
        </el-form-item>


        <el-form-item>
          <el-button v-loading.fullscreen.lock="loading" style="width: 100px;" type="primary"
                     @click="SubmitForm">保存
          </el-button>
        </el-form-item>

      </div>
    </el-form>

  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import {openDetails, productEdit} from '@/api/product'
  import {getToken} from "../../utils/auth";
  import {numberMultiply, parseTime, showDecimal, toInteger} from '@/utils';

  export default {
    name: 'commodityListDetail',
    components: {
      Tinymce
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        uploadAction: window.API_BASE_URI + "/files/upload",
        headers: {
          'User-Token': getToken(),
          'User-Platform': 'management'
        },
        formParams: {
          formId: "",
          coverImage: "",
          detail: "",
          enable: true,
          name: "",
          originalPrice: "",
          originalPriceFormat: "",
          pictures: "",
          price: "",
          priceFormat: "",
          queue: "",
          baseSaleCount: "",
          settlePrice: "",
          settlePriceFormat: "",
          groupBuySuccess: 20,
          groupBuySuccessUser: 3,
          groupBuyFailedAwardFormat: "5.00",
          groupBuyFailedAward: 500,
          groupBuyContributionFormat: "3.00",
          groupBuyContribution: 300,
          groupBuyBonusFormat: "20.00",
          groupBuyBonus: 2000,
          startSaleTimeDate: 0,
          startSaleTime: 0,
        },
        loading: false,
        dialogMapVisible: false,
        checked: '',
        imgList: [],
        params: {
          targetId: ''
        }
      }
    },
    computed: {},
    methods: {
      deleteImg(index) {
        this.imgList.splice(index, 1)
      },
      initData() {
        let id = this.$route.params.id
        if (id > 0) {
          this.params.targetId = id
          //分类详情
          openDetails(this.params).then((res) => {
            if (res.code === 200) {
              this.formParams = {
                formId: res.data.id,
                coverImage: res.data.coverImage,
                detail: res.data.detail,
                enable: res.data.enable,
                name: res.data.name,
                priceFormat: res.data.price / 100,
                originalPriceFormat: res.data.originalPrice / 100,
                settlePriceFormat: res.data.settlePrice / 100,
                baseSaleCount: res.data.baseSaleCount,
                queue: res.data.queue,
                groupBuySuccess: res.data.groupBuySuccess,
                groupBuySuccessUser: res.data.groupBuySuccessUser,
                groupBuyFailedAwardFormat: res.data.groupBuyFailedAward / 100,
                groupBuyContributionFormat: res.data.groupBuyContribution / 100,
                groupBuyBonusFormat: res.data.groupBuyBonus / 100,
                startSaleTimeDate: res.data.startSaleTime > 0 ? new Date(res.data.startSaleTime) : new Date(),
                startSaleTime: res.data.startSaleTime,
              }
              this.imgList = res.data.pictures;
            }
          })
        }
      },
      handleAvatarSuccess(res) {
        this.formParams.coverImage = window.API_BASE_URI + "/files/stream?fileName=" + encodeURIComponent(res.data);
        // console.log(this.formParams.coverImage);
      },
      aa(res) {
        if (this.imgList.length < 5) {
          this.imgList.push(window.API_BASE_URI + "/files/stream?fileName=" + encodeURIComponent(res.data));
          console.log(this.imgList, "this.imgList");
        }

      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!(isJPG || isPNG)) {
          this.$message.error('上传图片只能是 JPG|PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
      },
      // 保存
      SubmitForm() {
        this.formParams.price = numberMultiply(this.formParams.priceFormat, 100);
        this.formParams.originalPrice = numberMultiply(this.formParams.originalPriceFormat, 100);
        this.formParams.settlePrice = numberMultiply(this.formParams.settlePriceFormat, 100);
        this.formParams.groupBuyFailedAward = numberMultiply(this.formParams.groupBuyFailedAwardFormat, 100);
        this.formParams.groupBuyContribution = numberMultiply(this.formParams.groupBuyContributionFormat, 100);
        this.formParams.groupBuyBonus = numberMultiply(this.formParams.groupBuyBonusFormat, 100);
        this.formParams.startSaleTime = this.formParams.startSaleTimeDate.getTime();

        if (this.formParams.name === '') {
          this.$message.error('商品名称不能为空');
          return
        }
        if (this.formParams.price === '') {
          this.$message.error('商品售价不能为空');
          return
        }

        if (this.formParams.originalPrice === '') {
          this.$message.error('商品原价不能为空');
          return
        }

        if (this.formParams.coverImage === '') {
          this.$message.error('商品封面必传');
          return
        }
        if (this.imgList.length === 0) {
          this.$message.error('请至少上传至少一张轮播图片');
          return
        }
        if (this.formParams.detail === '') {
          this.$message.error('商品详情内容不能为空');
          return
        }

        if (this.formParams.queue === '') {
          this.$message.error('排列顺序不能为空');
          return
        }

        this.loading = true;
        this.formParams.pictures = this.imgList;

        productEdit(this.formParams).then((json) => {
          this.loading = false
          if (json.code === 200) {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
            this.$refs.Tinymce.destroyTinymce()
            this.$router.push({name: 'commodityList'});
          } else {
            this.$message({
              message: json.message,
              type: 'error'
            })
          }
        })
      }
    },
    mounted() {
      this.initData()
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  @import "src/styles/mixin.scss";

  #commodityListDetail {
    margin: 30px 35px 30px 0;
    .el-tree-node.is-expanded > .el-tree-node__children {
      display: flex;
      flex-direction: column;
      .el-tree-node.is-expanded > .el-tree-node__children {
        display: flex;
        flex-direction: row;

      }
    }
    .createPost-container {
      position: relative;
      .createPost-main-container {
        padding: 40px 45px 20px 50px;
        .postInfo-container {
          position: relative;
          @include clearfix;
          margin-bottom: 10px;
          .postInfo-container-item {
            float: left;
          }
        }
        .editor-container {
          min-height: 500px;
          margin: 0 0 30px;
          .editor-upload-btn-container {
            text-align: right;
            margin-right: 10px;
            .editor-upload-btn {
              display: inline-block;
            }
          }
        }
      }
      .word-counter {
        width: 40px;
        position: absolute;
        right: -10px;
        top: 0px;
      }
    }

    .avatar {
      height: 100px;
    }
    .select {
      width: 300px;
      margin-left: 20px;
    }
    .textFont {
      font-size: 16px;
      color: #333333;
    }
    .imgWrap {
      width: 100%;
      height: 100px;
      display: flex;
      justify-content: flex-start;

      .imgBox {
        margin-right: 20px;
        position: relative;
        img {
          /*width: 100px;*/
          height: 100px;
          margin-right: 10px;
        }
        .el-icon-remove {
          position: absolute;
          right: 0;
          top: -5px;
          font-size: 22px;
          color: red;
        }
      }

    }
  }

</style>
